﻿using MicroBlog.Services;

namespace MicroBlog.Data
{
    /// <summary>
    /// 初始化数据库
    /// </summary>
    public static class Initializer
    {
        const string defaultAdminUserName = "DefaultAdminUsername";
        const string defaultAdminPassword = "DefaultAdminPassword";

        public static async Task InitializeDatabaseAsync(IServiceProvider serviceProvider, bool createUsers = true)
        {
            using (var serviceScope = serviceProvider.CreateScope())
            {
                var scopeServiceProvider = serviceScope.ServiceProvider;
                var db = scopeServiceProvider.GetService<MicroBlogContext>();

                if (await db.Database.EnsureCreatedAsync())
                {
                    if (createUsers)
                    {
                        await CreateAdminUser(scopeServiceProvider);
                    }
                }
            }
        }
        /// <summary>
        /// 创建管理员账号
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        private static async Task CreateAdminUser(IServiceProvider serviceProvider)
        {
            var env = serviceProvider.GetService<IWebHostEnvironment>();

            //获取配置文件中的内容
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .AddEnvironmentVariables();
            var configuration = builder.Build();

            var userManager = serviceProvider.GetService<IUserManager>();

            var user = await userManager.FindByNameAsync(configuration[defaultAdminUserName]);
            if (user == null)
            {
                var result = await userManager.CreateAsync(configuration[defaultAdminUserName], configuration[defaultAdminPassword]);
                var role = new Models.Role { Name = "Administrator", Description = "超级管理员" };
                await userManager.CreateRoleAsync(role);
                int userId = 0;
                int.TryParse(result.Message, out userId);
                if (userId > 0 && role.Id > 0)
                {
                    await userManager.AddToRole(userId, role.Name);
                }
            }
        }
    }
}
